package com.huobao.yunying.activitys;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huobao.yunying.base.HuobaoBaseActivity;
import com.huobao.yunying.entity.DingdanDetail;
import com.huobao.yunying.entity.DingdanDetail_good_list;
import com.huobao.yunying.entity.DingdanDetail_orderextm;
import com.huobao.yunying.entity.Gouwuche_spec;
import com.huobao.yunying.entity.Gouwuche_specification;
import com.huobao.yunying.entity.Tuikuan;
import com.huobao.yunying.https.Http;
import com.huobao.yunying.https.HttpConst;
import com.huobao.yunying.https.HttpListener;
import com.huobao.yunying.https.HttpUtil;
import com.huobao.yunying.utils.BitmapTools;
import com.huobao.yunying.utils.ImageUtils;
import com.huobao.yunying.utils.ThreadPoolUtils;
import com.huobao.yunying.utils.UserUtils;
import com.huobao.yunying.utils.Utils;
import com.huobao.yunying.utils._PopupString;
import com.huobao.zhangying.R;
import com.xrz.sxm.base.utils.Log2File;
import com.xrz.sxm.base.utils.ToolLoading;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import net.bither.util.NativeUtil;

public class Act_Ask_Tuihuo extends HuobaoBaseActivity implements OnCheckedChangeListener, OnClickListener {

	private String order_id, goods_id;
	private TextView tv_bianhao;
	private TextView tv_price;
	private TextView tv_time;
	private TextView tv_select_yuanyi;
	private EditText edt_tuikuan_jine;
	private EditText edt_tui_yunfei;
	private RadioGroup radiogroup;
	private RadioButton rb_1;
	private RadioButton rb_2;
	private RadioButton rb_3;
	private EditText edt_tuihuo_shuoming;
	private ImageView img_1;
	private ImageView img_2;
	private ImageView img_3;
	private Button btn_1;

	private List<String> yuanyins;
	
	private Tuikuan tuikuan;
	

	private List<String> paths = new ArrayList<String>();

	//////////////////// 收货情况（0未收到货，需要退款 1已收到货，不退货只退款 2已收到货，需退货退款）
	@Override
	protected int getContentView() {
		// TODO Auto-generated method stub
		return R.layout.layout_ask_tuihuo;
	}

	@Override
	protected String getTitleText() {
		// TODO Auto-generated method stub
		return "退货/退款申请";
	}

	@Override
	protected void init() {
		tuikuan = (Tuikuan) getIntent().getSerializableExtra("data");
		order_id = getIntent().getStringExtra("order_id");
		goods_id = getIntent().getStringExtra("goods_id");
		initView();
		getYuanyins();
		if(tuikuan == null){
			getDingdanDetail();
		}else{
			show();
		}
		
	}

	private void show() {
		tv_bianhao.setText("订  单  号：" + tuikuan.order_sn);
		tv_price.setText("订单金额：¥" + tuikuan.order_amount);
		tv_time.setText("下单日期：" + tuikuan.add_time);
		tv_select_yuanyi.setText(tuikuan.refund_reason);
		edt_tuikuan_jine.setText(tuikuan.refund_fee);
		edt_tui_yunfei.setText(tuikuan.refund_shipping_fee);
		edt_tuihuo_shuoming.setText(tuikuan.refund_desc);
		shipped = tuikuan.shipped;
		if(tuikuan.shipped.equals("0")){
			rb_3.setChecked(true);
		}else if(tuikuan.shipped.equals("2")){
			rb_3.setChecked(true);
		}else if(tuikuan.shipped.equals("1")){
			rb_3.setChecked(true);
		}
		btn_1.setText("修改申请");
	}

	private void initView() {
		tv_bianhao = (TextView) findViewById(R.id.tv_bianhao);
		tv_price = (TextView) findViewById(R.id.tv_price);
		tv_time = (TextView) findViewById(R.id.tv_time);
		tv_select_yuanyi = (TextView) findViewById(R.id.tv_select_yuanyi);
		edt_tuikuan_jine = (EditText) findViewById(R.id.edt_tuikuan_jine);
		edt_tui_yunfei = (EditText) findViewById(R.id.edt_tui_yunfei);
		radiogroup = (RadioGroup) findViewById(R.id.radiogroup);
		rb_1 = (RadioButton) findViewById(R.id.rb_1);
		rb_2 = (RadioButton) findViewById(R.id.rb_2);
		rb_3 = (RadioButton) findViewById(R.id.rb_3);
		edt_tuihuo_shuoming = (EditText) findViewById(R.id.edt_tuihuo_shuoming);
		img_1 = (ImageView) findViewById(R.id.img_1);
		img_2 = (ImageView) findViewById(R.id.img_2);
		img_3 = (ImageView) findViewById(R.id.img_3);
		btn_1 = (Button) findViewById(R.id.btn_1);
		btn_1.setOnClickListener(this);
		tv_select_yuanyi.setOnClickListener(this);
		radiogroup.setOnCheckedChangeListener(this);
		img_1.setOnClickListener(this);
		img_2.setOnClickListener(this);
		img_3.setOnClickListener(this);
	}

	private String shipped;

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		// 收货情况（0未收到货，需要退款 1已收到货，不退货只退款 2已收到货，需退货退款）
		switch (checkedId) {
		case R.id.rb_1:
			shipped = "2";
			break;
		case R.id.rb_2:
			shipped = "1";
			break;
		case R.id.rb_3:
			shipped = "0";
			break;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_1:
			submit();
			break;
		case R.id.tv_select_yuanyi:
			_PopupString.showPop(context, yuanyins, v, new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					tv_select_yuanyi.setText(yuanyins.get(position));
					_PopupString.dismiss();
				}
			});
			break;
		case R.id.img_1:
			skipToSelectPic(1);
			break;
		case R.id.img_2:
			skipToSelectPic(2);
			break;
		case R.id.img_3:
			skipToSelectPic(3);
			break;
		}
	}

	private void skipToSelectPic(int requestCode) {
		Intent intent = new Intent(this, MultiImageSelectorActivity.class);
		// 是否显示拍摄图片
		intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
		// 最大可选择图片数量
		intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
		// 选择模式
		intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
		startActivityForResult(intent, requestCode);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 1:
			if (resultCode == RESULT_OK) {
				showPic(img_1, data);
			}
			break;
		case 2:
			if (resultCode == RESULT_OK) {
				showPic(img_2, data);
			}
			break;
		case 3:
			if (resultCode == RESULT_OK) {
				showPic(img_3, data);
			}
			break;
		}
	}

	private void showPic(ImageView img, Intent data) {
		List<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
		if (mSelectPath != null && mSelectPath.size() != 0) {
			paths.add(mSelectPath.get(0));
			img.setBackground(null);
			ImageUtils.loadimgFromSDcard(img, mSelectPath.get(0));
		}
	}

	/**
	 * TODO 输入验证,可根据需要自行修改补充
	 */
	private void submit() {
		// 开始验证输入内容
		String refund_goods_fee = edt_tuikuan_jine.getText().toString().trim();
		String refund_shipping_fee = edt_tui_yunfei.getText().toString().trim();
		String refund_desc = edt_tuihuo_shuoming.getText().toString().trim();
		String refund_reason = tv_select_yuanyi.getText().toString().trim();

		if (TextUtils.isEmpty(refund_goods_fee)) {
			Toast.makeText(this, "退款金额不能为空", Toast.LENGTH_SHORT).show();
			return;
		}

		if (TextUtils.isEmpty(refund_reason)) {
			Toast.makeText(this, "请选择退货理由", Toast.LENGTH_SHORT).show();
			return;
		}

		if (TextUtils.isEmpty(shipped)) {
			Toast.makeText(this, "请选择收货情况", Toast.LENGTH_SHORT).show();
			return;
		}

		// 首先上传图片
		ThreadPoolUtils.newInstant().submit(new Runnable() {

			@Override
			public void run() {
				ToolLoading.ShowLoading(context);
				uploadRes();
				handler.sendEmptyMessage(1);
			}
		});
	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 1) {
				ToolLoading.closeLoading(context);
				sunmit();
			}
		};
	};

	private String imageUrls = "";

	private void uploadRes() {
		if (paths.size() == 0)
			return;
		for (String path : paths) {
			Bitmap bitmap = BitmapTools.createImageThumbnail(path);
			if (bitmap == null)
				return;
			File f = new File(path);
			File newPath = new File(f.getParent(), f.getName() + "temp" + ".jpg");
			NativeUtil.compressBitmap(bitmap, 100, newPath.getAbsolutePath(), true);
			bitmap.recycle();
			String base64str = Base64.encodeToString(Utils.File2byte(newPath.getAbsolutePath()), Base64.NO_WRAP);
			Map<String, String> map = HttpUtil.getParams("app", "uploadpic", "act", "picupload", "type", "4", "user_id",
					UserUtils.getUserid(context) + "", "portrait", base64str);
			String result = Http.getInstant().sendRequestSync(HttpConst.UPLOAD_PHOTO_URL, map);
			JSONObject jsonObject = JSON.parseObject(result);
			String url = jsonObject.getString("retval");
			imageUrls += url + ",";
		}

	}

	protected void sunmit() {
		String refund_goods_fee = edt_tuikuan_jine.getText().toString().trim();
		String refund_shipping_fee = edt_tui_yunfei.getText().toString().trim();
		String refund_desc = edt_tuihuo_shuoming.getText().toString().trim();
		String refund_reason = tv_select_yuanyi.getText().toString().trim();

		String paths = "";
		if (imageUrls.equals("")) {
			paths = "";
		} else {
			paths = imageUrls.substring(0, imageUrls.length() - 1);
		}
		Map<String, String> map;
		if(tuikuan != null){
			map = HttpUtil.getParams("app", "buyerorder", "act", "editrefund", "refund_id", tuikuan.refund_id,
					 "refund_goods_fee", refund_goods_fee, "refund_shipping_fee", refund_shipping_fee,
					"shipped", shipped, "refund_desc", refund_desc, "refund_reason", refund_reason, "portrait", paths);
		}else{
			map = HttpUtil.getParams("app", "buyerorder", "act", "refund", "order_id", detail.order_id,
					"goods_id", goods_id, "refund_goods_fee", refund_goods_fee, "refund_shipping_fee", refund_shipping_fee,
					"shipped", shipped, "refund_desc", refund_desc, "refund_reason", refund_reason, "portrait", paths);
		}
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				String msg = jsonObject.getString("retval");
				Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
				finish();
			}

			@Override
			public void onHttpError(String error) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void getYuanyins() {
		Map<String, String> map = HttpUtil.getParams("app", "buyerorder", "act", "refund_reason");
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				yuanyins = JSON.parseArray(jsonObject.getString("retval"), String.class);
			}

			@Override
			public void onHttpError(String error) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void getDingdanDetail() {
		Map<String, String> map = HttpUtil.getParams("app", "buyerorder", "act", "view", "order_id", order_id);
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				JSONObject object = jsonObject.getJSONObject("retval");
				DingdanDetail detail = new DingdanDetail();
				detail.order_id = object.getString("order_id");
				detail.seller_id = object.getString("seller_id");
				detail.order_sn = object.getString("order_sn");
				detail.status = object.getString("status");
				detail.order_amount = object.getString("order_amount");
				detail.add_time = object.getString("add_time");
				detail.store_name = object.getString("store_name");
				detail.owner_name = object.getString("owner_name");
				detail.tel = object.getString("tel");
				detail.discount = object.getString("discount");
				detail.status_text = object.getString("status_text");

				JSONArray goods = object.getJSONArray("good_list");
				List<DingdanDetail_good_list> list = new ArrayList<DingdanDetail_good_list>();
				for (int i = 0; i < goods.size(); i++) {
					JSONObject jsonObject2 = goods.getJSONObject(i);
					DingdanDetail_good_list detail_good_list = new DingdanDetail_good_list();
					detail_good_list.goods_id = jsonObject2.getString("goods_id");
					detail_good_list.goods_name = jsonObject2.getString("goods_name");
					detail_good_list.price = jsonObject2.getString("price");
					detail_good_list.quantity = jsonObject2.getString("quantity");
					detail_good_list.goods_image = jsonObject2.getString("goods_image");

					List<Gouwuche_specification> specifications = new ArrayList<Gouwuche_specification>();
					JSONArray specificationArray = jsonObject2.getJSONArray("order_spec");
					if (specificationArray != null) {
						for (int k = 0; k < specificationArray.size(); k++) {
							JSONObject specificationObject = specificationArray.getJSONObject(k);
							Gouwuche_specification specification = new Gouwuche_specification();
							specification.spec_id = specificationObject.getString("spec_id");
							specification.spec_1 = specificationObject.getString("spec_1");
							specification.price = specificationObject.getFloatValue("price");
							specification.spec = JSON.parseArray(specificationObject.getString("spec"),
									Gouwuche_spec.class);
							specifications.add(specification);
						}
					}
					detail_good_list.specification = specifications;
					list.add(detail_good_list);
				}

				DingdanDetail_orderextm detail_orderextm = JSON.parseObject(object.getString("orderextm"),
						DingdanDetail_orderextm.class);
				detail.good_list = list;
				detail.orderextm = detail_orderextm;
				show(detail);
			}

			@Override
			public void onHttpError(String error) {
				// TODO Auto-generated method stub

			}
		});
	}

	private DingdanDetail detail;

	protected void show(DingdanDetail detail) {
		this.detail = detail;
		tv_bianhao.setText("订  单  号：" + detail.order_sn);
		tv_price.setText("订单金额：¥" + detail.order_amount);
		tv_time.setText("下单日期：" + detail.add_time);
	}
}
